#!/bin/sh /etc/rc.common
# Copyright (C) 2019-2020 Lienol <lawlienol@gmail.com>

START=99

CONFIG=brook_server
LOG_PATH=/var/log/$CONFIG
LOG_APP_FILE=$LOG_PATH/app.log

echolog() {
	echo -e "$(date "+%Y-%m-%d %H:%M:%S"): $1" >> $LOG_APP_FILE
}

gen_brook_config_file() {
	config_get enable $1 enable
	[ "$enable" = "0" ] && return 0
	config_get remarks $1 remarks
	config_get port $1 port
	config_get protocol $1 protocol
	config_get password $1 password
	
	/usr/bin/brook $protocol -l :$port -p $password >/dev/null 2>&1 &
	
	is_run=$(ps -w| grep -v grep | grep "brook $protocol -l :$port -p $password")
	if [ -z "$is_run" ];then
		echolog "$remarks $port Brook 运行失败" 
	else
		echolog "$remarks $port Brook 运行成功" 
	fi
}

start_brook_server() {
	mkdir -p $LOG_PATH
	touch $LOG_APP_FILE
	config_foreach gen_brook_config_file "user"
	fw3 reload >/dev/null 2>&1 &
}

stop_brook_server() {
	fw3 reload >/dev/null 2>&1
	ps -w | grep "brook server" | grep -v "grep" | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 &
	ps -w | grep "brook ssserver" | grep -v "grep" | awk '{print $1}' | xargs kill -9 >/dev/null 2>&1 &
	rm -rf $LOG_PATH
}

start() {
	config_load $CONFIG
	enable=$(uci -q get $CONFIG.@global[0].enable)
	if [ "$enable" = "0" ];then
		stop_brook_server
	else
		start_brook_server
	fi
}

stop() {
	stop_brook_server
}

restart() {
	stop
	start
}